#!/bin/bash

set -e  # 出错即退出
echo "开始安装 Deep Learning Platform 依赖环境..."

# ===============================
# Step 1: 设置镜像和代理（可选）
# ===============================
echo "设置镜像与代理环境..."

export ELECTRON_MIRROR=https://npmmirror.com/mirrors/electron/
export http_proxy=http://127.0.0.1:7890
export https_proxy=http://127.0.0.1:7890

# ===============================
# Step 2: 清理旧缓存
# ===============================
echo "清理 node_modules 与锁文件..."
rm -rf node_modules pnpm-lock.yaml

# ===============================
# Step 3: 安装所有依赖（允许 postinstall）
# ===============================
echo "安装依赖（允许运行脚本）..."
pnpm install

# ===============================
# Step 4: 检查 Electron 可执行文件
# ===============================
ELECTRON_BIN="node_modules/electron/dist/Electron.app/Contents/MacOS/Electron"

if [ -x "$ELECTRON_BIN" ]; then
  echo "✅ Electron 安装成功：$ELECTRON_BIN"
else
  echo "⚠️ Electron 未自动下载，尝试手动触发 install.js..."
  cd node_modules/electron
  node install.js
  cd - > /dev/null

  if [ -x "$ELECTRON_BIN" ]; then
    echo "✅ Electron 手动安装成功：$ELECTRON_BIN"
  else
    echo "❌ Electron 安装失败，请检查网络或权限问题！"
    exit 1
  fi
fi

# ===============================
# Step 5: 完成提示
# ===============================
echo ""
echo "🎉 所有依赖安装完成，你现在可以运行开发环境："
echo ""
echo "   pnpm run dev"
echo ""